﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;

namespace Inaction.UI
{
    public class ComponentCache
    {
        static ComponentCache instance;

        List<Component> componentList = new List<Component>();

        public static List<Component> Components
        {
            get { return instance == null ? null : instance.componentList; }
        }
        BarManager barManager;

        public static void InitCache()
        {
            if (instance == null)
            {
                instance = new ComponentCache();
            }
            instance.barManager = BarManagerDesigner.WorkingBarManager;
            instance.componentList.Clear();
            var components = instance.barManager.Container.Components.GetEnumerator();
            while (components.MoveNext())
            {
                var current = components.Current as Component;
                if (current != null)
                {
                    instance.componentList.Add(current);
                }
            }
        }

        public static IEnumerable<T> GetComponent<T>() where T : Component
        {
            foreach (var c in Components)
            {
                if (c is T)
                {
                    yield return (T)c;
                }
            }
        }

        public static BindingSource GetBindingSource(Type type)
        {
            foreach( var b in GetComponent<BindingSource>())
            {
                var t = b.DataSource as Type;
                if (t == null) continue;
                if (t.Assembly.FullName == type.Assembly.FullName && t.FullName == type.FullName) return b;
            }
            return null;
        }
    }
}
